package com.tsinkai.ettp.practice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Date;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;

public class RSA {
	
//	private static  String url = "https://www.cleanconnect.cn/api/cettc/user-logs?token=";
//	private static  String url = "https://www.cleanconnect.cn/api/cettc/logs?token=";
	private static  String url = "https://www.cleanconnect.cn/api/cettc/companies?token=";
	private static String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbXFd5v7wlZ65yo26bspp+liW8LoKWDcLFM/9ErGOV6leeOx6o+BTGekCaK6BkyjJvyTSSNuVWnbjfdTY8iIgGBKRH5IzYc1REhN9OUHJOfdtrBQ8VSwtokGPwsfQWISzfjNqNw6nx6MynorwMn4CmKwptlpMOusXMmXfdy9h2MwIDAQAB";
	private static  String src = null;
	//public key:MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKdUfCi0kdagixAobL45zgrf8PjjyQ35AwvpDbkl2ZBJbobhe1nJ6sFE2ijBaGd3Z9wCvvF4Fr/xqnuHGy5tEW0CAwEAAQ==
	//pravate key:MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEAp1R8KLSR1qCLEChsvjnOCt/w+OPJDfkDC+kNuSXZkEluhuF7WcnqwUTaKMFoZ3dn3AK+8XgWv/Gqe4cbLm0RbQIDAQABAkEAot/puvWIv5GlyySONNuvY4Z32Mxgd+lavc0sPnxJOdes4aTmtqOk2M3FooehkynlO/YDfAmv4WXKxuur+8g2AQIhANrTHLwoe73NDKdC743Mm4Kao3L9FTo6+Zgqn5hXJYXJAiEAw8HStfbl6zfy/PYTVI7ewE/WmUDvLHqb0avMRmQCEIUCIQCRGcYHGo0bCVnnm2H/0/oWe3YArMMjrrGM7k6PlNHjyQIhAKuCRqWsstZ6B4d/5YHBRwJBMOjGzoYuyhRSq7/EYVatAiBKSC99Q//oeMTiIo3Uviy0//1d8XLlzHei9R3SHrmB/A==
	private static final String rsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj+S6je7O2bOtVjXxd16HqtRMxDb4OI0C2jb0qVWn2+IWa7u6uMZ3HLY6AgzatvdzlolhjCz6rXhLVd/NNNIUSp7I7BDNiNcDHU1s/D0KeCp0CX98kJgsh92WOAsrvRLAG/WD3vVqkj6MEMAtKJ11LfDQQCb/6c4u8PCoCoDiTrCOZ6hojKVSOrbaXZUYuvA8qsKit0OagNr6GQ1QKyAGGqv37gyZPHk2DncvysDcyOGnQnbEqWPz7zhBbRziq/+0/MQTMSIy3PLf9/I/fCMU+UGJr1Qq4RMIaXFuRbfK2YQVpvMeDuGZ8TniczizcfHvJQNMk58Knn++CWl+1M/rqwIDAQAB";
	private static final String rsaPrivateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCP5LqN7s7Zs61WNfF3Xoeq1EzENvg4jQLaNvSpVafb4hZru7q4xncctjoCDNq293OWiWGMLPqteEtV38000hRKnsjsEM2I1wMdTWz8PQp4KnQJf3yQmCyH3ZY4Cyu9EsAb9YPe9WqSPowQwC0onXUt8NBAJv/pzi7w8KgKgOJOsI5nqGiMpVI6ttpdlRi68DyqwqK3Q5qA2voZDVArIAYaq/fuDJk8eTYOdy/KwNzI4adCdsSpY/PvOEFtHOKr/7T8xBMxIjLc8t/38j98IxT5QYmvVCrhEwhpcW5Ft8rZhBWm8x4O4ZnxOeJzOLNx8e8lA0yTnwqef74JaX7Uz+urAgMBAAECggEAaKCS+YMMSwW34vjEQ9yrXw6RZxblNBFsYokVK0+KB3sE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J0H1yFBNrfWizJk9WDVtj5PT2v1yTS6iE4gjoxaaYh4OZ6KxMtCoZt52vp4gv39dWXN/uWc0HS/Y867KTAUFllzIOSVK4RLPPpo=";
	
	
	static {
		JSONObject json = new JSONObject();
		json.put("payload", "cettc");
		json.put("timestamp", new Date().getTime());
		System.out.println(json.toString());
		src = json.toString();
	}
	 
	private static String input = src;
	public static void main(String[] args) {
//		rsaEncryptAndDecrypy();
//		System.out.println(rsaEncrypt());
		long start = System.currentTimeMillis();
		String httpUrl = getUrl();
		System.out.println(doGet(httpUrl));
		long end = System.currentTimeMillis();
		System.out.println(String.valueOf(end-start));
	}
	
	public static String getUrl() {
		
		String end_url = null;
		try {
			
			byte[] publicKeyBytes = Base64.decodeBase64(publicKeyStr);
			X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
			//加密
			Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPADDING");
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			byte[] result = cipher.doFinal(src.getBytes());
			System.out.println("encode:"+Base64.encodeBase64String(result));
			String token = Base64.encodeBase64String(result);
			token = URLEncoder.encode(token, "UTF-8");
			System.out.println(token);
			end_url = url + token+"&page=1&pagesize=30";
			System.out.println(end_url);
			
			} catch (Exception e) {
				e.printStackTrace();
			}
		return end_url;
	}
	
	public static void rsaEncryptAndDecrypy() {
		try {
			//1、公钥加密
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(rsaPublicKey)));
			
			Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			System.out.println(src.getBytes().length);
			byte[] encodeResult = cipher.doFinal(src.getBytes());
			
			
			//5、公钥加密、私钥解密——解密
			keyFactory = KeyFactory.getInstance("RSA");
			PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(rsaPrivateKey)));
			cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");
			cipher.init(Cipher.DECRYPT_MODE,privateKey);
			byte[] decodeResult  = cipher.doFinal(encodeResult);
			System.out.println("公钥加密、私钥解密——解密：" + new String(decodeResult));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	

	public static String rsaEncrypt() {
	    String result = "";
		try {
		    // 将Base64编码后的公钥转换成PublicKey对象
			byte[] buffer = Base64.decodeBase64(rsaPublicKey);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			PublicKey publicKey = keyFactory.generatePublic(keySpec);
			// 加密
			Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			byte[] inputArray = input.getBytes();
			int inputLength = inputArray.length;
			System.out.println("加密字节数：" + inputLength);
			// 最大加密字节数，超出最大字节数需要分组加密
			int MAX_ENCRYPT_BLOCK = 117;
			// 标识
			int offSet = 0;
			byte[] resultBytes = {};
			byte[] cache = {};
			while (inputLength - offSet > 0) {
				if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
					cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
					offSet += MAX_ENCRYPT_BLOCK;
				} else {
					cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
					offSet = inputLength;
				}
				resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
				System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
			}
			result = Base64.encodeBase64String(resultBytes);
		} catch (Exception e) {
			System.out.println("rsaEncrypt error:" + e.getMessage());
		}
		System.out.println("加密的结果：" + result);
		return result;
	}
	
	
	public static String doGet(String HttpUrl){
		HttpURLConnection connection = null;
		InputStream is = null;
		BufferedReader br = null;
		String result = null;
		
		try {
			//创建远程URL连接对象
			URL url = new URL(HttpUrl);
			//通过URL对象打开一个连接
			connection = (HttpURLConnection)url.openConnection();
			//设置请求方式
			connection.setRequestMethod("GET");
			//设置连接主机服务器的超时时间
			connection.setConnectTimeout(15000);
			//设置读取远程返回数据时间
			connection.setReadTimeout(60000);
			//发送请求
			connection.connect();
			if(connection.getResponseCode() == 200){
				//通过connection获取输入流
				 is = connection.getInputStream();
				//封装输入流，并设置编码
				 br = new BufferedReader(new InputStreamReader(is, "utf-8"));
				StringBuffer sbf = new StringBuffer();
				String temp = null;
				while((temp = br.readLine())!=null){
					sbf.append(temp);
					sbf.append("\r\n");
				}
				result = sbf.toString();
			}
			
			if(connection.getResponseCode() == 201){
				System.out.println("201");
				
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			connection.disconnect();
		}
		return result;
	}
}
